var fs = require("fs");
const fse = require("fs-extra");
const child_process = require("child_process");
const yarnPath = '/usr/local/bin/yarn';
const path = require('path');


// 检查目录层级深度
function checkDirectoryDepth(dirPath, maxDepth = 10) {
  try {
    const normalizedPath = path.normalize(dirPath);
    const parts = normalizedPath.split(path.sep).filter(part => part.length > 0);
    return parts.length <= maxDepth;
  } catch (err) {
    return false; // 处理异常情况
  }
}

// 检查目录中的文件数量
function checkFileCount(dirPath, maxFiles = 100) {
  try {
    const files = fs.readdirSync(dirPath);
    return files.length <= maxFiles;
  } catch (err) {
    return false;
  }
}

if (checkDirectoryDepth("./dist/lib") && checkFileCount("./dist/lib")){
  fs.rmdirSync("./dist/lib", { recursive: true, maxRetries: 3, retryDelay: 100 });
}


fse.copySync("./node_modules/semver-umd", "./dist/lib/semver-umd");
fse.copySync("./node_modules/vscode-oniguruma", "./dist/lib/vscode-oniguruma");
fse.copySync("./node_modules/vscode-textmate", "./dist/lib/vscode-textmate");


try {
  // 安全地删除目录
  if (fs.existsSync('./dist/extensions/vscode-web-playground')) {
    checkDirectoryDepth("./dist/extensions/vscode-web-playground") && checkFileCount("./dist/extensions/vscode-web-playground") && fs.rmdirSync("./dist/extensions/vscode-web-playground", { recursive: true, maxRetries: 3, retryDelay: 100 });
  }
} catch (error) {
  throw new Error( "Delete error,please check!" );
}

process.chdir('./extension-vscode-web-playground');
try {
  child_process.execFileSync(yarnPath, ['compile'], { stdio: 'inherit' });
} catch (error) {
  throw new Error('Failed to execute yarn compile:', error.message);
}

fse.ensureDirSync('../dist/extensions/vscode-web-playground/dist/')

// 使用 fs-extra 的 copySync 方法替代 cp 命令
fse.copySync('dist/extension.js', '../dist/extensions/vscode-web-playground/dist/extension.js');
